package com.shycloud.mido.member.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.member.api.entity.AtvAttendDetail;
import com.shycloud.mido.member.api.entity.AtvMainActive;
import com.shycloud.mido.member.api.entity.AtvMediaSpace;
import com.shycloud.mido.member.api.entity.AtvPlaysSimpleDate;
import com.shycloud.mido.member.api.util.Constant;
import com.shycloud.mido.member.api.util.DisplayConversionUtil;
import com.shycloud.mido.member.api.vo.AtvMainActivePageVO;
import com.shycloud.mido.member.api.vo.AtvMainActiveReqVO;
import com.shycloud.mido.member.api.vo.AtvMainActiveRespVO;
import com.shycloud.mido.member.api.vo.AtvMediaSpaceVO;
import com.shycloud.mido.member.service.AtvAttendDetailService;
import com.shycloud.mido.member.service.AtvMainActiveService;
import com.shycloud.mido.member.service.AtvMediaSpaceService;
import com.shycloud.mido.member.service.AtvPlaysSimpleDateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import springfox.documentation.annotations.ApiIgnore;


/**
 * @author bard.bai
 */
@RestController
@AllArgsConstructor
@RequestMapping("/v1/atv")
@Api(tags = "挑战赛-活动和老师")
@ApiIgnore
public class AtvMainController {

	private AtvMainActiveService atvMainActiveService;

	private AtvPlaysSimpleDateService atvPlaysSimpleDateService;
	/** 活动相册业务 service */
	private AtvMediaSpaceService spaceService;
	/** 活动详情模块 service */
	private AtvAttendDetailService detailService;

	@ApiOperation("保存或更新活动 ID存在则更新")
	@PostMapping("/saveOrUpdate")
	public R<Boolean> saveOrUpdate(@RequestBody @Valid AtvMainActiveReqVO vo) throws Exception {
		String memberId = SecurityUtils.getMember().getId();
		vo.setMemberId(memberId);
		atvMainActiveService.saveOrUpdateAtvMainActive(vo);
		return new R<Boolean>(true, "操作成功");
	}

	@ApiOperation("软删除活动")
	@GetMapping("/delete")
	public R<Boolean> delete(String id) throws Exception {
		if (StringUtils.isBlank(id)) {
			return new R<Boolean>(false, "活动ID必填");
		}
		atvMainActiveService.logicDeleteAtv(id);
		return new R<Boolean>(true, "操作成功");
	}


	@ApiOperation("分页查询活动列表-老师")
	@GetMapping("/page")
	public R<IPage<AtvMainActiveRespVO>> page(Long current, Long size, AtvMainActivePageVO vo)
			throws Exception {

		Page<AtvMainActiveRespVO> page = new Page<>(current, size);
		IPage<AtvMainActiveRespVO> result = atvMainActiveService.pageAtvMainActiveRespVO(page, vo);
		DisplayConversionUtil.transform(result);
		return new R<IPage<AtvMainActiveRespVO>>(result);
	}

	@ApiOperation("分页查询活动列表-老师APP机构下的活动")
	@GetMapping("/pageTeaApp")
	public R<IPage<AtvMainActiveRespVO>> pageTeaApp(Long current, Long size, AtvMainActivePageVO vo)
			throws Exception {

		Page<AtvMainActiveRespVO> page = new Page<>(current, size);
		IPage<AtvMainActiveRespVO> result = atvMainActiveService
				.pageAtvMainActiveRespVOTea(page, vo);
		DisplayConversionUtil.transform(result);
		return new R<IPage<AtvMainActiveRespVO>>(result);
	}

	@ApiOperation("分页查询活动列表-学生")
	@GetMapping("/pageStu")
	public R<IPage<AtvMainActiveRespVO>> pageStu(Long current, Long size, AtvMainActivePageVO vo)
			throws Exception {

		Page<AtvMainActiveRespVO> page = new Page<>(current, size);
		IPage<AtvMainActiveRespVO> result = atvMainActiveService
				.pageAtvMainActiveRespVOStu(page, vo);
		DisplayConversionUtil.transform(result);
		return new R<IPage<AtvMainActiveRespVO>>(result);
	}

	@ApiOperation("分页查询活动列表-学生-APP")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "current", value = "当前页", paramType = "query", dataType = "int",
					required = true),
			@ApiImplicitParam(name = "size", value = "每页显示条数", paramType = "query", dataType = "int",
					required = true),
			@ApiImplicitParam(name = "memberId", value = "老师ID", paramType = "query", dataType = "string",
					required = true),
			@ApiImplicitParam(name = "sponsorType", value = "类型0机构1官方", paramType = "query",
					dataType = "string", required = true)})
	@GetMapping("/pageStuApp")
	public R<IPage<AtvMainActiveRespVO>> pageStuApp(Long current, Long size, AtvMainActivePageVO vo,
			String teacherId)
			throws Exception {

		String memberId = SecurityUtils.getMember().getId();

		Page<AtvMainActiveRespVO> page = new Page<>(current, size);
		IPage<AtvMainActiveRespVO> result = atvMainActiveService
				.pageAtvMainActiveRespVOStu(page, vo);
		// 筛选【我参加的】数据，列出标识
		for (AtvMainActiveRespVO mainActive : result.getRecords()) {

			List<AtvAttendDetail> detailList = detailService
					.list(new QueryWrapper<AtvAttendDetail>()
							.eq(AtvAttendDetail.COL_MAIN_ACTIVE_ID, mainActive.getId())
							.eq(AtvAttendDetail.COL_MEMBER_ID, memberId));

			if (detailList.size() > 0) {
				mainActive.setIsMyJoin("1");
			} else {
				mainActive.setIsMyJoin("0");
			}
			// 判断是否是参加此活动的教师
			if (StringUtils.isNotEmpty(teacherId)) {
				//判断是否跟其中一个学生有关联
				mainActive.setIsTeacherInAct(
						detailService.getIsTeacherInAct(mainActive.getId(), teacherId));
			}

		}
		//[我参加的]置顶
		if (result.getRecords() != null) {
			List<AtvMainActiveRespVO> collect = result.getRecords().stream()
					.sorted((n1, n2) -> Integer.parseInt(n2.getIsMyJoin()) - Integer
							.parseInt(n1.getIsMyJoin()))
					.collect(Collectors.toList());
			result.setRecords(collect);
		}

		return new R<IPage<AtvMainActiveRespVO>>(result);
	}


	@ApiOperation("分页查询活动列表-无需登录")
	@GetMapping("/pageNoSession")
	public R<IPage<AtvMainActiveRespVO>> pageNoSession(Long current, Long size,
			AtvMainActivePageVO vo) throws Exception {
		if (StringUtils.isNotBlank(vo.getMemberId())) {
			return new R<IPage<AtvMainActiveRespVO>>(CommonConstants.FAIL, "用户不可查询", null);
		}
		Page<AtvMainActiveRespVO> page = new Page<>(current, size);
		IPage<AtvMainActiveRespVO> result = atvMainActiveService.pageAtvMainActiveRespVO(page, vo);
		DisplayConversionUtil.transform(result);
		return new R<IPage<AtvMainActiveRespVO>>(result);
	}

	@ApiOperation("查询活动详情")
	@GetMapping("/detail")
	public R<AtvMainActiveRespVO> detail(AtvMainActivePageVO vo) throws Exception {
		if (StringUtils.isBlank(vo.getId())) {
			return new R<AtvMainActiveRespVO>(CommonConstants.FAIL, "活动ID必填", null);
		}
		AtvMainActiveRespVO atvMainActiveRespVO = atvMainActiveService.getAtvMainActiveRespVO(vo);
		DisplayConversionUtil.transformOne(atvMainActiveRespVO);
		return new R<AtvMainActiveRespVO>(atvMainActiveRespVO);
	}

	@ApiOperation("查询活动状态(1未开始 2开启比赛 3进行中 4结束)")
	@GetMapping("/status")
	public R<Integer> status(AtvMainActivePageVO vo) throws Exception {
		if (StringUtils.isBlank(vo.getId())) {
			return new R<Integer>(CommonConstants.FAIL, "活动ID必填", null);
		}
		Integer status = atvMainActiveService.queryMainActiveStatus(vo.getId());
		return new R<Integer>(status);
	}

	@ApiOperation("查询活动类型")
	@GetMapping("/queryPlayTypeNoSession")
	public R<List<AtvPlaysSimpleDate>> queryPlayTypeNoSession() throws Exception {
		LambdaQueryWrapper<AtvPlaysSimpleDate> queryWrapper = Wrappers.<AtvPlaysSimpleDate>lambdaQuery()
				.eq(AtvPlaysSimpleDate::getDelFlag, Constant.DEL_FLAG)
				.eq(AtvPlaysSimpleDate::getEnable, "0");
		List<AtvPlaysSimpleDate> list = atvPlaysSimpleDateService.list(queryWrapper);
		return new R<List<AtvPlaysSimpleDate>>(list);
	}

	@PostMapping("addActvImgOrVideo")
	@ApiOperation(value = "上传图片或视频到活动相册", notes = "前端自己实现上传逻辑，本接口只接收视频及图片的URL(不包邮),需要传的字段:  \n"
			+ " 1.mainActiveId(活动ID)  \n" + " 2.mediaUrls(路径数组)  \n" + " 3.type(0-照片 1-视频)")
	public R<Boolean> addActvImgOrVideo(@RequestBody AtvMediaSpaceVO atvMediaSpaceVO) {

		if (atvMediaSpaceVO == null) {
			return new R(CommonConstants.FAIL, "所传参数不正确", false);
		}
		if (atvMediaSpaceVO.getMainActiveId() == null) {
			return new R(CommonConstants.FAIL, "mainActiveId 不能为空", false);
		}
		if (atvMediaSpaceVO.getMediaUrls() == null) {
			return new R(CommonConstants.FAIL, "mediaUrls 不能为空", false);
		}
		if (atvMediaSpaceVO.getType() == null) {
			return new R(CommonConstants.FAIL, "type 不能为空", false);
		}

		for (String mediaUrl : atvMediaSpaceVO.getMediaUrls()) {

			AtvMediaSpace atvMediaSpace = new AtvMediaSpace();

			BeanUtils.copyProperties(atvMediaSpaceVO, atvMediaSpace);
			// 正常数据
			atvMediaSpace.setDelFlag("0");
			// 创建时间
			atvMediaSpace.setCreateTime(new Date());
			// 创建用户
			atvMediaSpace.setCreateUser(SecurityUtils.getMember().getId());
			// 资源路径
			atvMediaSpace.setMediaUrl(mediaUrl);

			spaceService.save(atvMediaSpace);
		}
		return new R(true);
	}

	@ApiOperation("获取活动相册内容")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "current", value = "当前页", paramType = "query", dataType = "int",
					required = true),
			@ApiImplicitParam(name = "size", value = "每页显示条数", paramType = "query", dataType = "int",
					required = true),
			@ApiImplicitParam(name = "mainActiveId", value = "活动主键ID", paramType = "query",
					dataType = "string", required = true),
			@ApiImplicitParam(name = "type", value = "类型 0-图片 1-视频", paramType = "query",
					dataType = "string", required = true),
			@ApiImplicitParam(name = "memberId", value = "用户ID(如果传用户ID只查询当前用户的媒体 否则查询全部)",
					paramType = "query", dataType = "string", required = false)})
	@GetMapping("getActvImgOrVideo")
	public R getActvImgOrVideo(Integer current, Integer size, String mainActiveId, String type,
			String memberId) {
		Page page = new Page(current, size);
		AtvMainActive mainActive = atvMainActiveService.getById(mainActiveId);
		QueryWrapper<AtvMediaSpace> query =
				new QueryWrapper<AtvMediaSpace>().eq(AtvMediaSpace.COL_MAIN_ACTIVE_ID, mainActiveId)
						// 来源官网或者个人并且审核通过
						.eq(AtvMediaSpace.COL_TYPE, type)
						.and(wq -> wq.eq("source", "0")
								.or(wq2 -> wq2.eq("source", "1").eq("status", "1")));
		if (StringUtils.isNotBlank(memberId)
				&& !StringUtils.equals(mainActive.getMemberId(), memberId)) {
			query.eq(AtvMediaSpace.COL_CREATE_USER, memberId);// 删除自己
		}
		query.orderByDesc(AtvMediaSpace.COL_CREATE_TIME);
		IPage result = spaceService.page(page, query);

		List<AtvMediaSpace> atvMediaSpaces = result.getRecords();
		for (AtvMediaSpace atvMediaSpace : atvMediaSpaces) {
			//图片压缩
			if ("0".equals(atvMediaSpace.getType())) {
				atvMediaSpace.setMediaUrl(atvMediaSpace.getMediaUrl() + "?imageView2/2/w/1000/");
			}
		}
		result.setRecords(atvMediaSpaces);
		return new R(result);
	}

	@PostMapping("delActvImgOrVideo")
	@ApiImplicitParam(name = "ids", value = "图片或者视频的ID数组（注意：不是活动ID）", paramType = "query",
			dataType = "list", required = true)
	@ApiOperation("删除活动相册的图片或视频")
	public R delActvImgOrVideo(@RequestBody List<String> ids) {
		return new R(spaceService.removeByIds(ids));
	}

	@GetMapping("beginAtv")
	@ApiOperation("开启比赛")
	public R beginAtv(String mainActiveId) {
		return new R(detailService.beginAtv(mainActiveId));
	}

	@ApiOperation("APP获取活动相册内容")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "current", value = "当前页", paramType = "query", dataType = "int",
					required = true),
			@ApiImplicitParam(name = "size", value = "每页显示条数", paramType = "query", dataType = "int",
					required = true),
			@ApiImplicitParam(name = "mainActiveId", value = "活动主键ID", paramType = "query",
					dataType = "string", required = true),
			@ApiImplicitParam(name = "type", value = "类型 0-图片 1-视频", paramType = "query",
					dataType = "string", required = true),
			@ApiImplicitParam(name = "memberId", value = "用户ID(如果传用户ID只查询当前用户的媒体 否则查询全部)",
					paramType = "query", dataType = "string", required = false)})
	@GetMapping("getActvImgOrVideoApp")
	public R getActvImgOrVideoAPP(Integer current, Integer size, String mainActiveId, String type,
			String memberId) {

		// ============= 日期格式化 ======================//
		String strDateFormat = "yyyy-MM-dd";
		SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
		// =============日期格式化 ========================//

		Page page = new Page(current, size);

		AtvMainActive mainActive = atvMainActiveService.getById(mainActiveId);

		QueryWrapper<AtvMediaSpace> query =
				new QueryWrapper<AtvMediaSpace>().eq(AtvMediaSpace.COL_MAIN_ACTIVE_ID, mainActiveId)
						// 来源官网或者个人并且审核通过
						.eq(AtvMediaSpace.COL_TYPE, type)
						.and(wq -> wq.eq("source", "0")
								.or(wq2 -> wq2.eq("source", "1").eq("status", "1")));
		if (StringUtils.isNotBlank(memberId)
				&& !StringUtils.equals(mainActive.getMemberId(), memberId)) {
			query.eq(AtvMediaSpace.COL_CREATE_USER, memberId);
		}
		query.orderByDesc(AtvMediaSpace.COL_CREATE_TIME);

		List<AtvMediaSpace> atvMediaSpaces = spaceService.list(query);

		List<AtvMediaSpaceVO> resList = new ArrayList<>();

		for (AtvMediaSpace atvMediaSpace : atvMediaSpaces) {
			AtvMediaSpaceVO atvMediaSpaceVO = new AtvMediaSpaceVO();
			BeanUtils.copyProperties(atvMediaSpace, atvMediaSpaceVO);
			atvMediaSpaceVO.setCreateTimeGroup(sdf.format(atvMediaSpace.getCreateTime()));
			resList.add(atvMediaSpaceVO);
		}

		// 根据日期进行分组
		Map<String, List<AtvMediaSpaceVO>> dateGroupMap =
				resList.stream()
						.collect(Collectors.groupingBy(AtvMediaSpaceVO::getCreateTimeGroup));

		// map 排序
		LinkedHashMap<String, List<AtvMediaSpaceVO>> collect =
				dateGroupMap.entrySet().stream().sorted((x, y) -> {
					return y.getKey().compareTo(x.getKey());
				}).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
						(oldValue, newValue) -> oldValue, LinkedHashMap::new));

		return new R(collect);
	}

	/**
	 * @param current
	 * @param size
	 * @param province
	 * @param city
	 * @param memberId
	 * @return
	 * @Description: pageByLocation
	 * @author baiqiang.
	 * @date 2021年6月29日 下午6:48:20
	 * @version V1.0
	 */
	@ApiOperation("根据省市查询代理商的举办的活动详细")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "current", value = "当前页", paramType = "query", dataType = "int",
					required = true),
			@ApiImplicitParam(name = "size", value = "每页显示条数", paramType = "query", dataType = "int",
					required = true),
			@ApiImplicitParam(name = "province", value = "省", paramType = "query", dataType = "string",
					required = true),
			@ApiImplicitParam(name = "city", value = "市", paramType = "query", dataType = "string",
					required = true)})
	@GetMapping("pageByLocation")
	public R pageByLocation(Integer current, Integer size, String province, String city,
			String memberId) {
		Page<AtvMainActiveRespVO> page = new Page<AtvMainActiveRespVO>(current, size);
		return atvMainActiveService.pageByLocation(page, province, city, memberId);
	}

}
